<template>
    <el-form ref="messageForm" :model="messageFormData" status-icon :rules="messageRules" label-width="100px"
        class="demo-loginFormData">
        <el-form-item label="手机号" prop="number" class="check label">
            <el-input class="input1" v-model="messageFormData.number" maxlength="11" />
            <span @click="sendFn">{{ rework }}</span>
        </el-form-item>
        <el-form-item label="验证码" prop="identify" class="label">
            <el-input class="input" v-model="messageFormData.identify" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(messageForm)" class="button">登陆</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { onUnmounted, reactive, ref } from 'vue'
import { messageRules, useSubmitForm } from "../../composition/login/validate"
import * as api from "@/api/users"
import { useRouter } from 'vue-router';
import { ElMessage,ElLoading } from 'element-plus'
//引入store
import { useUser } from "@/store/users.js"
//使用store
let userStore = useUser()
let router = useRouter()
let validataSuccess = async () => {
    console.log('校验成功')
    //loading动画框调用
    let loadingInstance = ElLoading.service({
        lock: false,
        text: "正在登入。。。"
    })
    //发送短信登入的请求
    try {
        let res = await api.smsApi(messageFormData.identify)
        //登入成功，关闭loading动画
        loadingInstance.close()
        //存储token到sessionStorage中
        sessionStorage.setItem("my-token",res.data.token)
        //存储用户信息
        userStore.$patch({userInfo:res.data.userInfo})
        console.log(res);
        router.push("/")
    } catch (e) {
        console.log(e);
        //登入失败，也要关闭loading动画
        loadingInstance.close()
    }
}
let validataFaild = () => {
    console.log('校验失败')
}
let submitForm = useSubmitForm(validataSuccess, validataFaild)
const messageForm = ref()
//注入到表单的数据
const messageFormData = reactive({
    number: '',
    identify: '',
})
//短信登录流程
//1.输入手机号，点击发送按钮，获取短信验证码
//短信验证码需要进行倒计时提示
//手机验证码同一个手机号，一分钟只能发送一次，一天只能发送6次
//2.输入短信验证码，进行登录请求

//声明一个响应式变量，改变按钮中间的字（按钮的字不能是固定的，因为当点击后，按钮就变成倒计时的字了，所以必须使用响应式）
// let rework = ref('点击发送验证码')
// //定义点击事件
// let sendFn = () =>{
//     countdown (5,rework,'秒后重新发送')
// }
// //短信倒计时
// //封装倒计时方法
// /**
//  * 
//  * @param {Number} timer 倒计时的时间
//  * @param {Object} param 需要变更的响应式变量
//  * @param {String} msg 倒计时秒数的文字
//  * @param {String} endMsg 倒计时结束时的文字
//  */
// let countdown = (timer,param,msg,endMsg) =>{
//     let timerA = timer;
//     //当调用倒计时函数时，就要显示倒计时的秒数
//     param.value = (timerA+"").padStart(2,0) + msg
//     //使用间隔定时器

//     let interval = setInterval(() => {
//         timerA--
//         param.vlaue = endMsg
//         console.log(timerA)
//         if(timerA<0){
//             clearInterval(interval)
//             console.log(879797);
//             param.vlaue = "点击发送验证码"
//             return
//         }
//         param.value = (timerA+"").padStart(2,0) + msg
//     }, 1000);
//     console.log(interval)
// }
let rework = ref('点击发送验证码')
let count = null
let isopen = false
let sendFn = async () => {
    // isopen = false
    if (!isopen) {

        //发送获取短信验证码的请求
        try {
            let res = await api.getSmsCode(messageFormData.number)
            count = doneTime(60,

                () => {
                    isopen = false

                }

            )
            ElMessage({
                showClose: true,
                message: '短信发送成功',
                type: 'success',
            })
            console.log(res);
        } catch (e) {
            // console.log(e);
            ElMessage({
                showClose: true,
                message: e,
                type: 'error',
            })
            isopen = false
            return    //必须return，否则会执行下一步的isopen=true，使用return后，不走下一步，直接输出isopen=false的结果
        }
    }

    console.log("uuuuuuuuuu");
    isopen = true

}
//点击的时候文字发生变化
//1.改变文字===>点击的时候调用定时器
//2在定时器里放参数来改变参数
//编写定时器
let doneTime = (timer, cb) => {
    //核心方法：间隔定时器
    //核心思想：参数会--
    let interval = setInterval(() => {
        // rework.value = timer
        timer--
        console.log(timer);

        if (timer < 1) {
            //停掉定时器
            clearInterval(interval)
            console.log(interval, "oooooooooooooooo");
            console.log(timer, "timer");
            rework.value = '点击发送验证码'
            if (cb) {
                cb()
            }
            return
        }
        console.log(timer, "liting")
        rework.value = (timer + "").padStart(2, 0) + "秒后重新发送"
    }, 1000)
    console.log(rework.value);
    return interval
}
onUnmounted(() => {
    if (count) {
        clearInterval(count)
    }
})
</script>
<style lang="less" scoped>
.input {
    width: 250px;
}

.input1 {
    width: 140px;
    border-radius: 0 !important;
}

.button {
    width: 250px;
}

span {
    background-color: #fff;
    border-radius: 0 4px 4px 0;
    width: 110px;
    outline: none;
}

.check {
    :deep(.el-input__wrapper) {
        border-radius: 4px 0 0 4px;
        box-shadow: none;
    }
}

.label {
    :deep(.el-form-item__label) {
        color: #fff;
    }
}
</style>